package com.kly.user.utils;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.*;
import com.google.common.collect.Lists;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class GoogleStorageUtil {

    private static final String credentialsStr = "{\n" +
            "  \"type\": \"service_account\",\n" +
            "  \"project_id\": \"meboo-online-b68e7\",\n" +
            "  \"private_key_id\": \"1e6644124618042108718592c25cf603def7ac9e\",\n" +
            "  \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCX0dUf8fhe5isB\\ngS48korizvNNCVLH/vHmL5aF2PU3O6wlq2074Y/jERTGBa4CIuefgr9eCiRe4pQy\\noLcXJ7Qns2TXSc7mq65ewok5nI1gbjuKHbkP0H/TlwawkGLQt5b4xx3ElZkOB1yS\\nBztpiHPfiCHWtUi5eVkSPwEDyuefuQ8ug1HzjjS2KhNE85+kC0m3Cf3+qJJ0x4PR\\nak6YOJgTPGdPbGk88iuVwxTvKj2ls5eytkhHCTPTK8flWclyW1msA3Lsx7Fr6ZAe\\nTs43SGrjwMTI/g9rkW60AOdy3LRekBap7zsc3OLA7h/5PW4vgNsu2RPn5dwVCT+f\\neNVUkOzlAgMBAAECggEAANyW/ZRTXmOV+isK1KOlwMDMaVEFqeRUTvLqy9M3g3r5\\nH5bPdawuPA2XmVu55PC+PiMoq+WZ1ul+o6LKFRtUFSLNbCb9hiLFyFpeo+JefEAg\\nt4QhvNyshQ6vnbvuMPsj6EEZU8l5thQ9N6HCz0PDO8zsbqTWbXbMa6eoWy783o9/\\nl1/OIDbayoN7axo4ZGf9aotEy6szXlVR2HA7zX+dtMTRDwcCCpBAZCuM/SGEsJHw\\ngXkuFfY4JpV+sxCy8NVI1rdOg5KlYCZZbzg4K1NXmT9UlyqozFkvgRnB60vLbyyt\\nHH+zo1EbWnVB+SI9BYduaub0gzIYchiBMEHKbYXUxwKBgQDJO1L3+JZAJO697EN0\\nx5sCYwlDBDg3WFi/b/NPuxBEKuDR4miaI/XNkkLPTzH8MNaPEqaXbHhKOK6dAwbP\\ngd4oVZ3v9AA/NVA0SUhPvbNcYrZm7O7tTcmso8GcqB0M3SkpsWEDayPicziXKmOa\\nEsAaR9VwNUhD5lKFg5XWJS2LQwKBgQDBI8H1cF8p7WG83hBunGY3Ch6v6vTK1Xvh\\nkVWcYOU+ptJ91cOYbPSNcOa7fG3WcbNMJ7Lx7pEzvzWOhZjfshJgEXM7kfYqtWxh\\ny5Uaju69ZDTZuIMOVfOKEt2qAbTCZAe60NvBlKAbjw+OjJbHikKo86aOpg+ytV3R\\na6rTD14gtwKBgQCqYeKUNxTw5tSGVr+e50smMDitV6tJoTIzlVSMU7UoIq4MyAkN\\nShlbn9WVtlZ6U9e3eHE5kQwgu/GM2/0uQaWavTNm8lArNLbeLpZdfh+Zv7L1XvPG\\nVbDGzjimrek69R9fP+MGg/b0S97Ej42Z7PpexifARD0V0LRae9moYf44BQKBgGBY\\nKgT5TT9o/vxr+d5zfjmufqhamEomPGnFSeN8Il8icJX88Fk04Lk9vJuB8niqtzoi\\nA43T5/LcSycRVbUg6zGpAsaQhS/A2JPgLjzVWBp5xjNla1rXXWlfB9wqhbUCmSiD\\nz1u9fDDDKIt/bieTvLTy9f7qr6IB/w7cmpY2cEn5AoGASeEz56wYb4ivp8TfE41p\\nIyKkCIlNujoK+Rqv0pzgYW0AALS46ucZ+YAgvbgdk4czhyTBm7qMGRIwMPUstVhY\\n9rzZ/kvjbNVNI1V5eppURsMDeRmiDI9ciMs8LBrkvTEjfHeLMPjkJrqcwyHlN3Rn\\nuitW0SiCebjcm6ScdYvBV3Q=\\n-----END PRIVATE KEY-----\\n\",\n" +
            "  \"client_email\": \"credentialsforcloudstorage@meboo-online-b68e7.iam.gserviceaccount.com\",\n" +
            "  \"client_id\": \"114642442967846200136\",\n" +
            "  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" +
            "  \"token_uri\": \"https://oauth2.googleapis.com/token\",\n" +
            "  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" +
            "  \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/credentialsforcloudstorage%40meboo-online-b68e7.iam.gserviceaccount.com\",\n" +
            "  \"universe_domain\": \"googleapis.com\"\n" +
            "}";
    private static final String projectId = "meboo-online-b68e7";
    private static final String bucketName = "meboo-online-b68e7.appspot.com";

    public static void main(String[] args) throws IOException {

        uploadObject("apps/4.jpeg"  , "/Users/linqu/Downloads/20230619-193347.jpeg");
    }

    public static String uploadObject(/*String credentialsStr,
            String projectId, String bucketName, */String objectName, String filePath) throws IOException {
        // The ID of your GCP project
        // String projectId = "your-project-id";

        // The ID of your GCS bucket
        // String bucketName = "your-unique-bucket-name";

        // The ID of your GCS object
        // String objectName = "your-object-name";

        // The path to your file to upload
        // String filePath = "path/to/your/file"

        //读取本地存储的服务账号的json密钥，拿到该服务账号的权限
        GoogleCredentials credentials= GoogleCredentials.fromStream(new ByteArrayInputStream(credentialsStr.getBytes()))
                .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));


        Storage storage = StorageOptions.newBuilder().setProjectId(projectId).setCredentials(credentials).build().getService();
        BlobId blobId = BlobId.of(bucketName, objectName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();

        // Optional: set a generation-match precondition to avoid potential race
        // conditions and data corruptions. The request returns a 412 error if the
        // preconditions are not met.
        Storage.BlobWriteOption precondition;
        if (storage.get(bucketName, objectName) == null) {
            // For a target object that does not yet exist, set the DoesNotExist precondition.
            // This will cause the request to fail if the object is created before the request runs.
            precondition = Storage.BlobWriteOption.doesNotExist();
        } else {
            // If the destination already exists in your bucket, instead set a generation-match
            // precondition. This will cause the request to fail if the existing object's generation
            // changes before the request runs.
            precondition =
                    Storage.BlobWriteOption.generationMatch(
                            /*storage.get(bucketName, objectName).getGeneration()*/);
        }
//        storage.createFrom(blobInfo, Paths.get(filePath), precondition);

        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        Blob blob = storage.create(blobInfo, bytes);
        //修改已经上传的文件类型为 image/jpg
        blob.toBuilder().setContentType("image/jpg").build().update();

        System.out.println(
                "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);

        return objectName;
    }



}
